package com.leijie.nio;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author LeiJie
 * @time 2020-5-12 17:43
 * @desc 字符集问题
 */
public class NioTest13 {

    public static void main(String[] args) throws Exception{
        RandomAccessFile inputFile = new RandomAccessFile("input13.txt","r");
        RandomAccessFile outputFile = new RandomAccessFile("output13.txt","rw");

        long inputLength = new File("input13.txt").length();

        FileChannel inputChannel = inputFile.getChannel();
        FileChannel outputChannel = outputFile.getChannel();

        MappedByteBuffer inputBuffer = inputChannel.map(FileChannel.MapMode.READ_ONLY,0,inputLength);
        //内存映射文件
        byte[] fileBytes = new byte[(int) inputLength];
        for (int offset=0;offset<inputLength;offset++){
            fileBytes[offset] = inputBuffer.get();
        }
        System.out.println("文件读到的数据：\n"+new String(fileBytes));
        inputBuffer.rewind();
        Charset charset = StandardCharsets.ISO_8859_1;
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        CharBuffer decoderBuffer = decoder.decode(inputBuffer);

        System.out.println(charset.toString()+"解码后的数据:\n"+decoderBuffer.toString());

        ByteBuffer encoderBuffer = encoder.encode(decoderBuffer);

        System.out.println(charset.toString()+"编码后的数据:\n"+new String(encoderBuffer.array()));

        outputChannel.write(encoderBuffer);

        inputFile.close();
        outputFile.close();
    }

}
